# encoding: utf-8
"""
Tree交互模式
"""
import sys
from TVM.TVM import Interpreter
from Compiler.Compiler import Compiler
from share import ver
from loader.codes_loader import codes_dict


def tshell():
    """脚本"""
    # 欢迎语句
    print(f'Welcome to Tree {ver}.This is tshell.you can use "help()" to find help.\n')
    interpreter = Interpreter()
    while 1:
        instruction = input("\ntshell>").rstrip(" ")
        if instruction == "exit()":
            sys.exit()

        if len(instruction) >= 1 and instruction[-1] == "{":
            loop_codes = load_loop()
            loop_codes.insert(0, instruction)
            instruction = "\n".join(loop_codes)
        try:
            in_codes = Compiler(instruction)
            tempcodes = [[(codes_dict[j[0]], j[1]) for j in i] for i in in_codes[1]]
            interpreter.codes = tempcodes
            interpreter.values = in_codes[2]
            interpreter.names = in_codes[3]
            interpreter.classes.update(in_codes[4])
            interpreter.run_code()
        except SystemExit:
            pass


def load_loop(break_loop=1):
    """帮助获取跨越多行的代码"""
    code_list = []
    while 1:
        code = input(f'{break_loop * "    "}    ->').rstrip(" ")
        code_list.append(code)
        if len(code) >= 1 and code[-1] == "{":
            break_loop += 1
        elif len(code) >= 1 and code[-1] == "}":
            break_loop -= 1
            if break_loop == 0:
                break
    return code_list


if __name__ == "__main__":
    tshell()
